package com.training.hatton.dropboxclient.fragment;
import android.database.Cursor;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader; 
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.training.hatton.base.processor.BaseProcessor;
import com.training.hatton.dropboxclient.R;
import com.training.hatton.dropboxclient.adapter.FileListCursorAdapter;
import com.training.hatton.dropboxclient.content.Metadata;
import com.training.hatton.dropboxclient.content.contract.MetadataContract;
import com.training.hatton.dropboxclient.service.ServiceHelper;
import com.training.hatton.dropboxclient.utill.DropboxService;
import com.training.hatton.dropboxclient.utill.ProcessorCallbackListener;

public class DropboxListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, ProcessorCallbackListener{

	
	private static final String SELECTION = MetadataContract.MetadataColumns.PARENT + " = ? ";
	private static final String SORT_ORDER = MetadataContract.MetadataColumns.IS_DIR + " DESC, " + MetadataContract.MetadataColumns.NAME + " COLLATE NOCASE ASC";
	private FileListCursorAdapter mFileCursorAdapter;
	private boolean needRefresh = false;
	private Metadata mData;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Bundle data = getArguments();
		if (data != null){
			mData = new Metadata(data.getString(DropboxService.EXTRA_JSON));
		}else{
			mData = new Metadata(DropboxService.ROOT_METADATA);
		}
		mFileCursorAdapter = new FileListCursorAdapter(getActivity(), null);
		setListAdapter(mFileCursorAdapter);
		getLoaderManager().initLoader(0, null, this);
		super.onActivityCreated(savedInstanceState);
	}
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
	}
	
	@Override
	public void onResume() {
		ServiceHelper.get(getActivity()).registerProcessorCallbackListener(this);
		super.onResume();
	}
	@Override
	public void onPause() {
		((ProgressBar)getActivity().findViewById(R.id.progress)).setVisibility(View.GONE);
		ServiceHelper.get(getActivity()).removeProcessorCallbackListener(this);
		super.onPause();
	}
	
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle data) {
		String path = mData.getPath();
		return new CursorLoader(getActivity(), MetadataContract.MetadataColumns.CONTENT_URI, null, SELECTION, new String[]{path}, SORT_ORDER);
	}

	@Override 
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if(cursor != null && cursor.getCount()!= 0){
			needRefresh = false;
			mFileCursorAdapter.swapCursor(cursor);
		}else{
			if (needRefresh){
				return;
			}
			needRefresh = true;
			ServiceHelper.get(getActivity()).downloadMetadata(DropboxService.ROOT, mData.getPath());
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mFileCursorAdapter.swapCursor(null);
	}
	
	@Override
	public void onResult(int resultCode, Bundle resultData) {
		ProgressBar bar = (ProgressBar) getActivity().findViewById(R.id.progress);
		switch(resultCode){
		case BaseProcessor.SUCCESS_CODE:
			bar.setVisibility(View.GONE);
			break;
		case BaseProcessor.ERROR_CODE:
			bar.setVisibility(View.GONE);
			Toast.makeText(getActivity(), ((Exception)resultData.getSerializable(DropboxService.EXTRA_ERROR)).getMessage(), Toast.LENGTH_LONG).show();
			break;
		case BaseProcessor.START_CODE:
			bar.setVisibility(View.VISIBLE);
			break;
		}
		
	}
	
	@Override
	public void onListItemClick(ListView list, View v, int position, long id) {
		Cursor cursor = mFileCursorAdapter.getCursor();
		if (cursor.moveToPosition(position)) {
			if (cursor.getInt(cursor.getColumnIndex(MetadataContract.MetadataColumns.IS_DIR)) > 0) {
				replaceFragment(new DropboxListFragment(), cursor.getString(cursor.getColumnIndex(MetadataContract.MetadataColumns.JSON)));
			} else {
				replaceFragment(new DropboxDetailsFragment(), cursor.getString(cursor.getColumnIndex(MetadataContract.MetadataColumns.JSON)));
			}
		}
		super.onListItemClick(list, v, position, id);
	}
	
	private void replaceFragment(Fragment fragment, String json){
		Bundle data = new Bundle();
		data.putString(DropboxService.EXTRA_JSON, json);
		fragment.setArguments(data);
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		ft.replace(R.id.fragment_container, fragment);
		ft.addToBackStack(null);
		ft.commit();
	}
	
	public void setData(Metadata md){
		mData = md;
	}
	public Metadata getData(){
		return mData;
	}
}